package com.zgj.demojetpackapp.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.zgj.demojetpackapp.App
import com.zgj.demojetpackapp.room.dao.PersonDao
import com.zgj.demojetpackapp.room.dao.StudentDao
import com.zgj.demojetpackapp.room.po.PersonBean
import com.zgj.demojetpackapp.room.po.Student

/**
 *  @author Simple
 *  @date 2020/1/9
 *  @description ：
 **/
@Database(entities = [PersonBean::class], version = 4)
abstract class PersonRoomDatabase : RoomDatabase() {

    abstract fun personDao(): PersonDao

    companion object {

        @Volatile
        private var instance: PersonRoomDatabase? = null

        fun getPersonRoomDatabase(context:Context):PersonRoomDatabase{
            if (null == instance){
                synchronized(PersonRoomDatabase::class){
                    if (null == instance){
                        instance = Room.databaseBuilder(context.applicationContext,PersonRoomDatabase::class.java,"db_test")
                            .addMigrations(object: Migration(1,2){
                                override fun migrate(database: SupportSQLiteDatabase) {
                                    database.execSQL("CREATE TABLE IF NOT EXISTS `Student` (" +
                                            "`id` INTEGER PRIMARY KEY AUTOINCREMENT," +
                                            "`name` TEXT," +
                                            "`age` INTEGER " +
                                            ");")
                                }
                            })
                            .addMigrations(object :Migration(2,3){
                                override fun migrate(database: SupportSQLiteDatabase) {

                                }
                            })
                            .addMigrations(object :Migration(3,4){
                                override fun migrate(database: SupportSQLiteDatabase) {
                                    database.execSQL("DROP TABLE IF EXISTS `Student`")
                                }

                            })
                            .allowMainThreadQueries().build()
                    }
                }
            }
            return instance!!
        }

    }

}
